package com.itsu.graph_v2.component;

import com.itsu.graph_v2.entity.Dept;
import com.itsu.graph_v2.entity.Emp;
import com.itsu.graph_v2.service.DeptService;
import com.itsu.graph_v2.service.EmpService;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsData;
import com.netflix.graphql.dgs.DgsQuery;
import com.netflix.graphql.dgs.InputArgument;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

@DgsComponent
public class EmpComponent {

    @Autowired
    EmpService empService;


    @Autowired
    DeptService deptService;

    @DgsQuery
    public List<Emp> emps(@InputArgument Integer id) {

        List<Emp> emps = empService.findAll();

        if (ObjectUtils.isEmpty(id)) {
            return emps;
        }

        return emps.stream()
                .filter(emp -> emp.getId() == id)
                .collect(Collectors.toList());
    }


    @DgsData(parentType = "Emp",field = "dept")
    public Dept dept(DataFetchingEnvironment df){
        Emp emp = df.getSource();
        return deptService.findById(emp.getDeptId());
    }
}
